package dao;

import entity.DiaryInFo;
import util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DiaryDao {
    public void save(DiaryInFo di){//保存日记
        String sql="insert into diaryinfo(userId,diaryDay,weather,mood,contents,reportTime) values(?,?,?,?,?,?)";
        DBUtil.update(sql,di.toArray());
    }
    public void update(DiaryInFo di){//修改日记
        String sql="update diaryinfo set weather=?,mood=?,contents=?,reportTime=? where id=?";
        DBUtil.update(sql,di.getWeather(),di.getMood(),di.getContents(),di.getReportTime(),di.getId());
    }
    public DiaryInFo findById(Integer id){//通过id查找
       String sql="select * from diaryinfo where id=?" ;
        ResultSet rs= DBUtil.find(sql,id);
        try {
            rs.next();
            DiaryInFo di=getDiaryInfo(rs);
            return di;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public  void delect(String sql){

    }
    public List<DiaryInFo> findAll() {//查找所有
        List<DiaryInFo> list=new ArrayList<>();
        try {
            ResultSet rs = DBUtil.find("select * from diaryinfo");
            while (rs.next()) {
                DiaryInFo di =getDiaryInfo(rs);
                list.add(di);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
return list;
    }
    private DiaryInFo getDiaryInfo(ResultSet rs) throws SQLException {
        DiaryInFo di=new DiaryInFo();
        di.setId(rs.getInt("id"));
        di.setUserId(rs.getInt("userId"));
        di.setDiaryDay(rs.getDate("diaryDay"));
        di.setMood(rs.getString("mood"));
        di.setContents(rs.getString("contents"));
        di.setWeather(rs.getString("weather"));
        di.setReportTime(rs.getTime("reportTime"));
        return di;
    }
     public static void main(String[] args){
////        DiaryDao dd= new DiaryDao();
////        DiaryInFo di=dd.findById(1);
////        di.setContents("我想说点什么？");
//////       dd.update(di);
////        System.out.println(di);
////        List<DiaryInFo> lists=dd.findAll();
////        for (DiaryInFo d:lists){
////            System.out.println(d);
////        }
        DiaryInFo di=new DiaryInFo();
        di.setUserId(1);
        di.setDiaryDay(new Date());
        di.setWeather("阴");
        di.setMood("好");
        di.setContents("嘻嘻嘻嘻嘻嘻嘻嘻嘻，哈哈哈哈哈哈哈啊哈哈哈哈哈啊哈哈哈<br/>hahahhahahahhahhahah");
        di.setReportTime(new Date());
        DiaryDao dd= new DiaryDao();
        dd.save(di);

   }
}
